import BaseScene from './core/BaseScene';
import PopupManager from './core/PopupManager'
import SceneNavigator from './core/SceneNavigator';
import { Commands } from './net/Commond';
import { HttpRequest } from './net/HttpRequest'
import { StorageUtil } from './utils/StorageUtil';
const { ccclass, property } = cc._decorator;

@ccclass
export default class login extends BaseScene {
    @property(cc.EditBox) edx_username: cc.EditBox = null
    @property(cc.EditBox) edx_password: cc.EditBox = null

    onLoad() {
        SceneNavigator.setHome('loginScene')
        // cc.game.addPersistRootNode(myNode);
        let local_username = StorageUtil.ins().getItem('local_username');
        let local_password = StorageUtil.ins().getItem('local_password');
        local_username && (this.edx_username.string = local_username);
        local_password && (this.edx_password.string = local_password);
    }
    onLoginClick() {
        let username = this.edx_username.string;
        let password = this.edx_password.string;
        this.loginUser(username, password)
    }

    loginUser(username, password) {
        let httpPromise = HttpRequest.ins().httpPromise(Commands.login, { username: username, password: password }, 'get', () => {
            console.log('错误处理1')
        })
        httpPromise.then((data) => {
            PopupManager.show('prefabs/PopBox', {
                title: '提示',
                content: '登录成功',
                confirmCallback: () => {
                    console.log('关闭弹窗')
                    StorageUtil.ins().setItem('local_username', username);
                    StorageUtil.ins().setItem('local_password', password);
                    SceneNavigator.go('chatScene', {})
                }
            })
        }).catch(() => {
            console.log('错误处理2')
        })
    }

    onRegisterClick() {
        let username = this.edx_username.string;
        let password = this.edx_password.string;
        this.registerUser(username, password)
    }

    registerUser(username, password) {
        let httpPromise = HttpRequest.ins().httpPromise(Commands.reg, { username: username, password: password }, 'get', () => {
            console.log('错误处理1')
        })
        httpPromise.then((data: any) => {
            PopupManager.show('prefabs/PopBox', {
                title: '提示',
                content: data.msg,
                confirmCallback: () => {
                    console.log('关闭弹窗')
                }
            })
        }).catch(() => {
            console.log('错误处理2')
        })
    }


}
